package com.qf.push.controller;

import com.qf.base.dto.push.MessageDTO;
import com.qf.base.result.R;
import com.qf.push.dao.MessageDao;
import com.qf.push.model.Message;
import com.qf.push.server.WebSocketServer;
import com.qf.push.service.PushService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 汤奇
 * @version V1.0
 * @Project BookPro
 * @Package com.qf.push.controller
 * @Description:
 * @Date 2022/8/8 20:42
 */
@RestController
@RequestMapping("qf/push")
public class PushController {
    @Resource
    private PushService pushService;

    @Resource
    private WebSocketServer webSocketServer;

    @PostMapping("push2web")
    public R push2Web(@RequestBody MessageDTO messageDTO){
        Long uid = messageDTO.getUid();
        String message = messageDTO.getMessage();
        boolean result = webSocketServer.sendInfo(uid.toString(), message);
        Message msg = new Message();
        msg.setUid(uid);
        msg.setContent(message);
        msg.setServiceId(messageDTO.getServiceId());
        msg.setLastTime(messageDTO.getLastTime());

        if (result){
            msg.setState(1);
            pushService.saveMessage(msg);
            return R.ok("发送成功");
        } else {
            msg.setState(0);
            pushService.saveMessage(msg);
            return R.ok("用户离线, 推送任务已经设置");
        }
    }
}
